#!/usr/bin/python
# -*- coding: UTF-8 -*-
from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
    )
from django.utils import timezone


class AppUserManager(BaseUserManager):
    """
    应用用户管理
    """

    def create_user(self, email, nickname, sex, register_code, password=None):
        """
        Creates and saves a User with the given email, password, etc.
        """
        if not email:
            raise ValueError('用户必须使用一个电邮.')

        # 'nickname', 'sex', 'register_code', 'password'
        user = self.model(
            email=self.normalize_email(email),
            nickname=nickname,
            sex=sex,
            register_code=register_code,
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, nickname, sex, register_code, password):
        u = self.create_user(email, nickname, sex, register_code, password)
        u.is_admin = True
        u.save(using=self._db)
        return u


class AppUser(AbstractBaseUser):
    """
    应用用户
    """
    email = models.EmailField(max_length=150, unique=True, db_index=True)
    is_admin = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    date_joined = models.DateTimeField(default=timezone.now)
    nickname = models.CharField(max_length=100)
    sex = models.BooleanField(default=False)
    # 不使用外键的形式，以提高用户表查询的效率。
    register_code = models.CharField(max_length=50, unique=False, db_index=True)

    objects = AppUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['nickname', 'sex', 'register_code', 'password']

    class Meta:
        db_table = 'hqz_auth_app_user'

    def get_full_name(self):
        return self.nickname

    def get_short_name(self):
        return self.nickname

    def __unicode__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        """
        Does the user have a specific permission?
        """
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        """
        Does the user have permissions to view the app `app_label`?
        """
        # Simplest possible answer: Yes, always
        return True

    # Admin required fields
    @property
    def is_staff(self):
        """
        Is the user a member of staff?
        """
        # Simplest possible answer: All admins are staff
        return self.is_admin